import { CLOUD_CONFIG } from '../../cloud-config.js'

export default class SimpleCloudManager {
  constructor() {
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.gameStarted = false
    this.openid = null
    
    // 回调函数
    this.onRoomCreated = null
    this.onRoomJoined = null
    this.onGameStart = null
    this.onMoveReceived = null
    this.onGameOver = null
    this.onOpponentConnected = null
    this.onOpponentDisconnected = null
    
    this.initCloud()
  }

  // 初始化云开发
  initCloud() {
    try {
      if (typeof wx !== 'undefined' && wx.cloud) {
        console.log('正在初始化云开发，环境ID:', CLOUD_CONFIG.envId)
        
        wx.cloud.init({
          env: CLOUD_CONFIG.envId,
          traceUser: true
        })
        
        console.log('云开发初始化成功')
      } else {
        console.warn('云开发不可用')
        throw new Error('云开发不可用')
      }
    } catch (error) {
      console.error('云开发初始化失败:', error)
      throw error
    }
  }

  // 生成房间ID
  generateRoomId() {
    return Math.random().toString(36).substr(2, 6).toUpperCase()
  }

  // 获取用户openid
  async getOpenid() {
    if (!this.openid) {
      try {
        const { result } = await wx.cloud.callFunction({
          name: 'getOpenId'
        })
        this.openid = result.openid
      } catch (error) {
        console.error('获取openid失败:', error)
        // 使用随机ID作为备选
        this.openid = 'user_' + Math.random().toString(36).substr(2, 9)
      }
    }
    return this.openid
  }

  // 调用云函数
  async callCloudFunction(type, data = {}) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'roomManager',
        data: {
          type: type,
          openid: this.openid,
          ...data
        }
      })
      return result
    } catch (error) {
      console.error('调用云函数失败:', error)
      return {
        success: false,
        message: '网络错误'
      }
    }
  }

  // 创建房间
  async createRoom() {
    try {
      console.log('创建房间...')
      
      const openid = await this.getOpenid()
      const roomId = this.generateRoomId()
      
      console.log('创建房间参数:', { openid, roomId })
      
      // 调用云函数创建房间
      const result = await this.callCloudFunction('create_room', {
        roomId: roomId,
        playerName: '玩家1'
      })
      
      if (result.success) {
        this.roomId = roomId
        this.playerId = openid
        this.isCreator = true
        this.gameStarted = false
        
        console.log('房间创建成功:', roomId)
        
        // 开始轮询房间状态
        this.startPolling()
        
        if (this.onRoomCreated) {
          this.onRoomCreated(roomId, true)
        }
        
        return roomId
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('创建房间失败:', error)
      throw error
    }
  }

  // 加入房间
  async joinRoom(roomId) {
    try {
      console.log('加入房间:', roomId)
      
      const openid = await this.getOpenid()
      
      // 调用云函数加入房间
      const result = await this.callCloudFunction('join_room', {
        roomId: roomId,
        playerName: '玩家2'
      })
      
      if (result.success) {
        this.roomId = roomId
        this.playerId = openid
        this.isCreator = false
        this.gameStarted = false
        
        console.log('房间加入成功:', roomId)
        
        // 开始轮询房间状态
        this.startPolling()
        
        if (this.onRoomJoined) {
          this.onRoomJoined(roomId, false)
        }
        
        return roomId
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('加入房间失败:', error)
      throw error
    }
  }

  // 开始轮询房间状态
  startPolling() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
    }
    
    this.pollingTimer = setInterval(() => {
      this.pollRoomStatus()
    }, 1000) // 每秒轮询一次
  }

  // 停止轮询
  stopPolling() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
      this.pollingTimer = null
    }
  }

  // 轮询房间状态
  async pollRoomStatus() {
    if (!this.roomId) return
    
    try {
      const result = await this.callCloudFunction('get_room_info', {
        roomId: this.roomId
      })
      
      if (result.success) {
        const roomData = result.data
        this.handleRoomUpdate(roomData)
      }
    } catch (error) {
      console.error('轮询房间状态失败:', error)
    }
  }

  // 处理房间更新
  handleRoomUpdate(roomData) {
    // 检查游戏是否开始
    if (roomData.status === 'playing' && !this.gameStarted) {
      this.gameStarted = true
      
      if (this.onGameStart) {
        this.onGameStart()
      }
      
      if (this.onOpponentConnected) {
        this.onOpponentConnected()
      }
    }
    
    // 检查游戏是否结束
    if (roomData.status === 'finished' && roomData.winner !== null) {
      if (this.onGameOver) {
        this.onGameOver(roomData.winner)
      }
    }
    
    // 检查对手是否断开连接
    if (roomData.status === 'waiting' && this.gameStarted) {
      this.gameStarted = false
      
      if (this.onOpponentDisconnected) {
        this.onOpponentDisconnected()
      }
    }
  }

  // 下棋
  async makeMove(row, col, player) {
    if (!this.roomId) {
      throw new Error('未在房间中')
    }
    
    try {
      const result = await this.callCloudFunction('make_move', {
        roomId: this.roomId,
        row: row,
        col: col,
        player: player
      })
      
      if (result.success) {
        if (this.onMoveReceived) {
          this.onMoveReceived(result.data)
        }
        
        return result.data
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('下棋失败:', error)
      throw error
    }
  }

  // 离开房间
  async leaveRoom() {
    if (!this.roomId) return
    
    try {
      await this.callCloudFunction('leave_room', {
        roomId: this.roomId,
        playerName: this.isCreator ? '玩家1' : '玩家2'
      })
    } catch (error) {
      console.error('离开房间失败:', error)
    } finally {
      this.stopPolling()
      this.roomId = null
      this.playerId = null
      this.isCreator = false
      this.gameStarted = false
    }
  }

  // 获取分享链接
  getShareLink() {
    if (!this.roomId) return null
    
    return {
              title: '象棋对战',
      path: `/pages/game/game?roomId=${this.roomId}`,
      imageUrl: '/images/share.jpg'
    }
  }

  // 清理资源
  cleanup() {
    this.stopPolling()
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.gameStarted = false
    this.openid = null
  }
} 